package cn.com.generaldata.os.service.impl.web;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.nutz.dao.impl.sql.SqlTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.newpojo.ReportVersion;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.result.ReportVersionYearRangeResult;

@Component
public class VersionServiceForWeb {

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<ReportVersion> versionDAO;

	@Autowired
	private SqlTemplate indicatorSystemSqlTemplate;

	/**
	 * 添加版本.
	 */

	/**
	 * 取得版本列表.
	 */

	public List<ReportVersion> getVersionList() {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("versionNumber");
		List<ReportVersion> versionList = versionDAO.find(ReportVersion.class, filter, null);

		// 有实际报表数据的，不允许删除
		for (ReportVersion v : versionList) {
			String hql = "from Version v where versionNumber = ? and exists (select 1 from Report r where r.reportVersion = ?)";
			List<ReportVersion> resultList = versionDAO.findByHql(hql, v.getVersionNumber(), v.getVersionNumber());
			//			if (resultList.size() > 0) {
			//				v.setAllowDelete(0);
			//			} else {
			//				v.setAllowDelete(1);
			//			}
		}
		return versionList;
	}

	/**
	 * 更新版本.
	 */

	/**
	 * 激活版本.
	 */

	public void activeVersion(ReportVersion version) {

		// 之前的版本变为未激活
		String hql = "from Version v where active = ?";
		List<ReportVersion> resultList = versionDAO.findByHql(hql, 1);
		for (ReportVersion v : resultList) {
			v.setActive(0);
			versionDAO.update(v);
		}

		// 该版本激活
		version.setActive(1);
		versionDAO.update(version);
	}

	public ReportVersionYearRangeResult getReportVersionYearRange() {
		ReportVersionYearRangeResult result = new ReportVersionYearRangeResult();
		Date startYear = indicatorSystemSqlTemplate.queryForObject("SELECT MIN(start_date) FROM tbl_report_version ",
				null, Date.class);
		Date endYear = indicatorSystemSqlTemplate.queryForObject("SELECT MAX(end_date) FROM tbl_report_version ", null,
				Date.class);
		Calendar cal = Calendar.getInstance();
		cal.setTime(startYear);
		result.setStartYear(cal.get(Calendar.YEAR));
		cal.setTime(endYear);
		result.setEndYear(cal.get(Calendar.YEAR));
		return result;
	}
}
